package com.zhkjnet.zhyy.service;

import com.zhkjnet.zhyy.ZhyyConfiguration;
import com.zhkjnet.zhyy.dao.AssetDao;
import com.zhkjnet.zhyy.entity.Asset;
import com.zhkjnet.zhyy.entity.User;
import com.zhkjnet.zhyy.dao.UserDao;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.List;

@Service
public class UserService {
	
	private final static Logger logger = LoggerFactory.getLogger(UserService.class);
    @Autowired
    private UserDao userDao;

    @Autowired
    private AssetDao assetDao;

    @Autowired
    private ZhyyConfiguration configuration;

    private String addSalt(String text) {
        return DigestUtils.md5DigestAsHex((configuration.getSalt() + text).getBytes());
    }

    @Transactional
    public void save(User user, Long minMoney) {
        user.setCreateTime(new Date());
        user.setPassword(addSalt(user.getPassword()));
        userDao.save(user);
        Asset asset = new Asset();
        asset.setMoney(0L);
        asset.setUser(user);
        asset.setAbleMoney(0L);
        asset.setMinMoney(minMoney);
        asset.setMinCashback(0L);
        asset.setCashback(0L);
        assetDao.save(asset);
    }

    public User findByPhoneAndPassword(String phone, String password) {
        return userDao.findByPhoneAndPassword(phone, addSalt(password));
    }

    @Transactional
    public void deleteById(Long id) {
        User user = new User();
        user.setId(id);
        user.setDeleted(true);
        userDao.update(user);
    }

    public User login(String phone, String password) {
        return userDao.findByPhoneAndPassword(phone, password);
    }

    public List<User> findAll(Long page, Integer length) {
        return userDao.findAll((page - 1) * length, length );
    }

    public Long count() {
        return userDao.count();
    }

    public User findById(Long id) {
        return userDao.findById(id);
    }

    @Transactional
    public void updatePassword(Long id, String password) {
        User user = new User();
        user.setId(id);
        logger.info("user="+id+",update password="+password);
        user.setPassword(addSalt(password));
        userDao.update(user);
    }

}
